#!/usr/bin/env python3
#-*- coding:utf-8 -*-
"""
" http server for ip2Region
"
" Author: wkt<weikting@gmail.com>
" Date : 2019-01-23
"""
import sys,socket,json
from ip2Region import Ip2Region

class IPInfo:

    def __init__(self,dbfile=None):
        if dbfile is None:
            dbfile = '../../data/ip2region.db'
        self._dbFile = dbfile
        self._searcher = Ip2Region(self._dbFile)
    
    def _getIPs(self,host):
        infos=socket.getaddrinfo(host,0)
        res = None
        for i in infos:
            if res is None:
                res = []
            ip=i[4][0]
            if ip in res:continue
            res.append(ip)
        return res

    def _ipInfo(self,ip,btree=True):
        vv = self._searcher.btreeSearch(ip) if btree else self._searcher.memorySearch()
        rgn = vv['region'].decode("utf8")
        vv= rgn.split('|')
        country=vv[0]
        area=vv[1]
        region=vv[2]
        city=vv[3]
        isp=vv[4]
        return {
                'country':country if (country != '0' and country != 0) else '',
                'area':area if (area != '0' and area != 0) else '',
                'region':region if (region != '0' and region != 0) else '',
                'city':city if (city != '0' and city != 0) else '',
                'isp':isp if (isp != '0' and isp != 0) else ''
                }

    def getInfo(self,host,btree=True):
        ips = self._getIPs(host)
        res = None
        for i in ips:
            if res is None:
                res = []
            res.append(self._ipInfo(i,btree))
        return res

import bottle
from bottle import route,request,response

ipInfo=None

@route('/')
@route('/<host>')
def index(host=None):
    global ipInfo
    res={'code':-1}
    try:
        if host is None:
            host = request.environ.get('REMOTE_ADDR')
        all = request.params.get('all')
        if ipInfo is None:
            ipInfo = IPInfo()
        aa = ipInfo.getInfo(host)
        res['data'] = aa if all else aa[0]
    except Exception as e:
        res['msg']=e.args[0]
    response.set_header('Server','ws/1.0')
    response.set_header('Content-Type', 'application/json; charset=UTF-8')
    return json.dumps(res)

def httpdRun():
    bottle.run(host='0.0.0.0',port='8080')


if __name__ == "__main__":
    httpdRun()
